package com.example.springboot2022nocv.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot2022nocv.entity.Menu;
import com.example.springboot2022nocv.entity.User;
import com.example.springboot2022nocv.service.MenuService;
import com.example.springboot2022nocv.service.RoleService;
import com.example.springboot2022nocv.utils.TreeNode;
import com.example.springboot2022nocv.utils.TreeNodeBuilder;
import com.example.springboot2022nocv.vo.DataView;
import com.example.springboot2022nocv.vo.MenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;


@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/toMenu")
    public String toMenu(){
        return "menu/menu";
    }

    @RequestMapping("/loadAllMenu")
    @ResponseBody
    public DataView loadAllMenu(MenuVo menuVo){
        IPage<Menu> page = new Page<>(menuVo.getPage(),menuVo.getLimit());
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(menuVo.getTitle()),"title",menuVo.getTitle());
        queryWrapper.orderByAsc("ordernum");
        menuService.page(page);
        return  new DataView(page.getRecords());
    }
    //加载下拉菜单数据 和左侧数据dtree
    @RequestMapping("loadMenuManagerLeftTreeJson")
    @ResponseBody
    public DataView loadMenuManagerLeftTreeJson(){
        List<Menu> list = menuService.list();
        ArrayList<TreeNode> treeNodes = new ArrayList<>();
        for(Menu menu:list){
            Boolean  open = menu.getOpen() == 1?true:false;
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),open));
        }
        return new DataView(treeNodes);
    }
    //赋值最大的排序吗+1
    @RequestMapping("/menu/loadMenuMaxOrderNum")
    @ResponseBody
    public Map<String,Object> loadMenuMaxOrderNum(){
            Map<String,Object> map = new HashMap<>();
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("ordernum");
            IPage<Menu> page = new Page<>(1,1);
            List<Menu> list = menuService.page(page, queryWrapper).getRecords();
            map.put("value",list.get(0).getOrdernum()+1);
            return map;
    }
    //新增菜单
    @RequestMapping("/addMenu")
    @ResponseBody
    public DataView addMenu(Menu menu){
        DataView dataview = new DataView();
        menu.setType( "menu");
        boolean save = menuService.save( menu);
        if ( !save){
            dataview.setCode(100);
            dataview.setMsg("数据插入失败");
        }
        dataview.setMsg("菜单插入成功!");
        dataview.setCode(200);
        return dataview;
    }

    @RequestMapping("/updateMenu")
    @ResponseBody
    public DataView updateMenu (Menu menu){
        menuService.updateById(menu);
        DataView dataview = new DataView();
        dataview.setCode(200);
        dataview.setMsg("更新菜单成功!");
        return dataview;
    }

    @RequestMapping( "/checkMenuHaschildrenNode")
    public Map<String,Object>checkchildrenNode(Menu menu) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<Menu> querywrapper = new QueryWrapper<>();
        querywrapper.eq("pid", menu.getId());
        List<Menu> list = menuService.list(querywrapper);
        if (list.size() > 0) {
            map.put("value ", true);
        } else {
            map.put("value", false);
        }
        return map;
    }

    @RequestMapping("/deleteMenu")
    @ResponseBody
    public DataView deleteMenu(Menu menu){
        menuService.removeById(menu.getId());
        DataView dataview = new DataView();
        dataview.setCode(200);
        dataview. setMsg("更新菜单成功!");
        return dataview;
    }

    /***
    加载主页面index的菜单栏，带有层级关系
    ***/
    @RequestMapping("/loadIndexLeftMenuJson")
    @ResponseBody
    public DataView loadIndexLeftMenuson(Menu menu, HttpSession session){
        //查询所有菜单栏
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        List<Menu> list = null;
        //1.按照条件查询[超级管理员,学生,老师,院长]取出session中的用户ID
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();

        if (user.getUsername().equals("admin")||StringUtils.equals(user.getUsername(),"admin")){
            list =  menuService.list();
        }else {
            //2.根据用户ID查询角色
            List<Integer> currentUserRoleIds = roleService.queryUserRoleById(userId);
            //3.根据角色ID查询菜单栏ID
            //去重
            Set<Integer> mids = new HashSet<>();
            for (Integer rid : currentUserRoleIds){
                //根据角色id查询菜单
                List<Integer> permissionIds = roleService.queryAllpermissionByRid(rid);
                //菜单栏id和角色Id去重
                mids.addAll(permissionIds);
            }
            //根据角色ID查询菜单Id
            if(mids.size()>0){
                queryWrapper.in("id",mids);
                list = menuService.list(queryWrapper);
            }
        }



        //构造层级关系
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Menu m : list){
            Integer id = m.getId();
            Integer pid = m.getPid();
            String title = m.getTitle();
            String icon = m.getIcon();
            String href = m.getHref();
            Boolean open = m.getOpen().equals(1) ?true: false;
            treeNodes.add(new TreeNode(id,pid,title,icon,href,open));
        }
        //层级关系
        List<TreeNode> nodeList = TreeNodeBuilder.build(treeNodes,0);
        return new DataView(nodeList);
    }


}
